// pages/earnings/earnings.js
import api from '../../utils/api';
import Notify from '@vant/weapp/notify/notify';
Page({
  data: {
    balance: 0.00,
    withdrawalAmount: 0.00, // 新增：用户输入的提现金额
    withdrawalHistory: [],
    totalWithdrawn: 0.00, // 新增：累计提现总额
    bankInfo: {
      hasBindCard: false,
      cardNumber: ''
    }
  },

  onLoad: function (options) {
    this.fetchUserEarnings();
    this.fetchWithdrawalHistory();
    // 从缓存读取银行卡信息
    this.loadBankInfo();
  },

  onShow: function () {
    // 每次页面显示时重新读取银行卡信息，确保从绑定页面返回后能及时更新
    this.loadBankInfo();
  },

  // 加载银行卡信息
  loadBankInfo: function() {
    const bankInfo = wx.getStorageSync('bankInfo');
    if (bankInfo && bankInfo.cardNumber && bankInfo.bankName && bankInfo.realName) {
      this.setData({
        'bankInfo.cardNumber': bankInfo.cardNumber,
        'bankInfo.bankName': bankInfo.bankName,
        'bankInfo.realName': bankInfo.realName,
        'bankInfo.hasBindCard': true
      });
      console.log('已加载银行卡信息:', bankInfo);
    } else {
      // 如果没有银行卡信息，重置状态
      this.setData({
        'bankInfo.hasBindCard': false,
        'bankInfo.cardNumber': '',
        'bankInfo.bankName': '',
        'bankInfo.realName': ''
      });
      console.log('未找到银行卡信息，需要绑定');
    }
  },

  // 获取用户收益信息
  fetchUserEarnings: function () {
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      Notify({ type: 'danger', message: '未获取到用户ID' });
      return;
    }
    
         // 调用后端接口获取用户余额
     api.getUserBalance(userId).then(res => {
       console.log('获取余额接口返回:', res);
       if (res.data && (res.data.code === 0 || res.data.code === 200)) {
         // 根据实际返回的数据结构解析
         // 后端返回: { code: 200, data: { code: 200, data: { availableBalance: 393.36 } } }
         const balanceData = res.data.data || {};
         const balance = balanceData.availableBalance || balanceData.available_balance || balanceData.balance || balanceData.amount || 0;
         this.setData({
           balance: parseFloat(balance).toFixed(2)
         });
         console.log('获取到用户余额:', balance);
         console.log('完整返回数据:', res.data);
       } else {
         console.error('获取余额失败，返回数据:', res.data);
         Notify({ type: 'danger', message: '获取余额失败' });
         // 如果获取失败，使用默认值
         this.setData({
           balance: 0.00
         });
       }
     }).catch(err => {
       console.error('获取余额失败:', err);
       Notify({ type: 'danger', message: '获取余额失败' });
       // 如果获取失败，使用默认值
       this.setData({
         balance: 0.00
       });
     });
  },

  // 获取提现历史
  fetchWithdrawalHistory: function () {
    const userId = wx.getStorageSync('userId'); // 从本地缓存获取userId
    if (!userId) {
      Notify({ type: 'danger', message: '未获取到用户ID' });
      return;
    }
         api.getWithdrawalRecordsByUserId(userId).then(res => {
       console.log('获取提现记录接口返回:', res);
       if (res.data && (res.data.code === 0 || res.data.code === 200)) {
         // 假设返回的数据结构为 { code: 0, data: [ {id, amount, status, apply_time}, ... ] }
         const withdrawalHistory = res.data.data || [];
         console.log('提现记录数据:', withdrawalHistory);
         
         // 计算累计提现总额
         const totalWithdrawn = withdrawalHistory.reduce((total, record) => {
           return total + (parseFloat(record.amount) || 0);
         }, 0);
         
         this.setData({
           withdrawalHistory: withdrawalHistory,
           totalWithdrawn: totalWithdrawn.toFixed(2)
         });
      } else {
        Notify({ type: 'danger', message: '获取提现记录失败' });
      }
    }).catch(err => {
      Notify({ type: 'danger', message: '获取提现记录失败' });
    });
  },

  // 输入提现金额
  inputWithdrawalAmount: function(e) {
    const amount = parseFloat(e.detail.value) || 0;
    this.setData({
      withdrawalAmount: amount
    });
  },

  // 提现操作
  handleWithdraw: function () {
    const userId = wx.getStorageSync('userId');
    const availableBalance = this.data.balance;
    const withdrawalAmount = this.data.withdrawalAmount;
    const bankInfo = this.data.bankInfo;
    
    // 校验银行卡信息
    if (!userId || !bankInfo.cardNumber || !bankInfo.bankName || !bankInfo.realName) {
      Notify({ type: 'danger', message: '请先绑定完整的银行卡信息' });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/bind-card/bind-card' });
      }, 1000);
      return;
    }
    
    // 校验提现金额
    if (!withdrawalAmount || withdrawalAmount <= 0) {
      Notify({ type: 'danger', message: '请输入提现金额' });
      return;
    }
    
    if (withdrawalAmount < 10) {
      Notify({ type: 'danger', message: '单笔最低提现金额为10元' });
      return;
    }
    
    if (withdrawalAmount > availableBalance) {
      Notify({ type: 'danger', message: '提现金额不能超过可用余额' });
      return;
    }
    
    // 校验银行卡号格式
    if (!/^[0-9]{16,19}$/.test(bankInfo.cardNumber)) {
      Notify({ type: 'danger', message: '银行卡号格式不正确' });
      return;
    }
    
    wx.showModal({
      title: '提现确认',
      content: `确定要提现 ¥${withdrawalAmount} 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '提交中' });
          api.applyWithdraw(userId, withdrawalAmount, bankInfo.cardNumber, bankInfo.bankName, bankInfo.realName).then(resp => {
            wx.hideLoading();
                         if (resp.data && (resp.data.code === 0 || resp.data.code === 200)) {
               Notify({ type: 'success', message: '提现申请已提交' });
               // 清空输入框
               this.setData({
                 withdrawalAmount: 0
               });
               // 重新获取余额和提现记录
               this.fetchUserEarnings();
               this.fetchWithdrawalHistory();
            } else {
              Notify({ type: 'danger', message: resp.data.msg || '提现失败' });
            }
          }).catch(() => {
            wx.hideLoading();
            Notify({ type: 'danger', message: '提现失败' });
          });
        }
      }
    });
  },

  // 绑定银行卡
  bindBankCard: function () {
    wx.navigateTo({
      url: '/pages/bind-card/bind-card',
    });
  },

  // 查看提现详情
  viewWithdrawalDetail: function (e) {
    const item = e.currentTarget.dataset.item;
    if (!item) {
      Notify({ type: 'danger', message: '数据异常' });
      return;
    }
    
    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return '未知时间';
      try {
        const date = new Date(timeStr);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      } catch (e) {
        return timeStr;
      }
    };
    
    // 格式化状态
    const formatStatus = (status) => {
      switch (status) {
        case 'SUCCESS':
        case '已完成':
          return '已完成';
        case 'PENDING':
        case '处理中':
          return '处理中';
        case 'FAILED':
        case '失败':
          return '失败';
        default:
          return status || '处理中';
      }
    };
    
         // 构建详情内容
     const detailContent = `
 提现详情：
 • 提现金额：¥${item.amount}
 • 提现状态：${formatStatus(item.status)}
 • 申请时间：${formatTime(item.applyTime || item.apply_time || item.createTime || item.date)}
 • 提现ID：${item.id || '未知'}
 • 银行卡：${item.bankName || '未知'}
 • 持卡人：${item.realName || '未知'}
 • 卡号：${item.bankCard ? item.bankCard.replace(/(\d{4})\d+(\d{4})/, '$1****$2') : '未知'}
     `.trim();
    
    wx.showModal({
      title: '提现详情',
      content: detailContent,
      showCancel: false,
      confirmText: '确定'
    });
  }
}) 